package com.it.security.handle;

import com.alibaba.fastjson.JSON;
import com.it.base.resposne.JsonData;
import com.it.security.JWTUser;
import com.it.security.utils.JwtAuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: learning
 * @description: 认证成功处理器
 * @author: Lefnmg
 * @create: 2018-11-19 21:42
 **/
@Component
public class SuccessfulAuthHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtAuthUtils jwtAuthUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        JWTUser user = (JWTUser)authentication.getPrincipal();
        String token = jwtAuthUtils.generateToken(user);
        JsonData data = JsonData.ok().put("token", token);
        httpServletResponse.getWriter().write(JSON.toJSONString(data));
    }
}
